package zz.extjs.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import zz.extjs.factory.DAOFactory;

public class GetList extends HttpServlet { // 提供零散数据访问，json形式返回记录

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		PrintWriter out = response.getWriter();

		//登录检查
		Object zz = request.getSession().getAttribute("user1");

		if (zz == null) { // 先检查用户是否处于登入状态
			response.sendRedirect("logout.jsp");
			return;
		}

		String par = request.getParameter("par"); // querystring 标志参数
		String course = request.getParameter("cos"); // querystring course

		try { // 将ISO-8859-1转为UTF-8，可能会有变化
			if(course!=null)
				course = new String(course.getBytes("ISO-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException ex) {
			course = null;
		}

		/**
		 * 暂时忽略参数检验
		 */

		// 遇到问题，exam表中scope是字符型,维持原状
		// int r = -1;
		try {
			if ("cos_count".equals(par)) { // 请求首页上的统计信息
				JSONArray js = DAOFactory.getDatasetDAOInstance().getCosCount(
						null);

				int arr[] = { 0, 0, 0 };
				for (int i = 0; i < js.length(); i++) { // 加入合计记录
					if ("基本课程"
							.equals(js.getJSONObject(i).getString("cos_name")))
						arr[0] += js.getJSONObject(i).getInt("count");
					else if ("深化课程".equals(js.getJSONObject(i).getString(
							"cos_name")))
						arr[1] += js.getJSONObject(i).getInt("count");
					else if ("双学位课程".equals(js.getJSONObject(i).getString(
							"cos_name")))
						arr[2] += js.getJSONObject(i).getInt("count");
				}

				for (int i = 0; i < 4; i++) { // i：0-2为各课程小计，3为汇总合计
					JSONObject record = new JSONObject(); // 拷贝一条记录
					record.put("sex", i == 3 ? "" : "合计");
					record.put("cos_name", i == 0 ? "基本课程" : (i == 1 ? "深化课程"
							: (i == 3 ? " 总计" : "双学位课程")));
					record.put("count", i == 3 ? arr[0] + arr[1] + arr[2]
							: arr[i]);
					js.put(record);
				}

				out.print("{course:'" + course + "'");
				out.print(",root:");
				out.print(js.toString());
				out.print("}");

			} else if ("sub_cmbo".equals(par)) { // 表示请求subject名称列表
				JSONArray js = DAOFactory.getDatasetDAOInstance().getSubName(
						course);
				/*
				 * //为简化开发，不再合并course，省略下述算法 JSONArray jout = new JSONArray();
				 * JSONObject jtmp = new JSONObject(); int offset = 0;
				 * //记录js因course重复被移除个数，在用i-offset来获得当前元素的位置 //String str = "|";
				 * int count = js.length();
				 * 
				 * for(int i=0;i<count;i++){ //
				 * [{course:'基本课程',subnames:[{text:'xxx'},{text:'yyy'}]},{...}]
				 * //思路，顺序遍历js，遇到course与前相同则删除，并把text填入前面的text数组, int k = i -
				 * offset; //就算移除后的实际位置 String cos =
				 * js.getJSONObject(k).getString("cos"); if(!(jtmp.has(cos))){
				 * js.getJSONObject(k).put("subnames", new
				 * JSONArray("[{text:'"+js
				 * .getJSONObject(k).getString("text")+"'}]")); jtmp.put(cos,
				 * jtmp.length()); js.getJSONObject(k).remove("text"); //str +=
				 * js.getJSONObject(0).getString("course")+"|"; }else{
				 * JSONObject jmv = (JSONObject)(js.remove(k));
				 * js.getJSONObject(
				 * jtmp.getInt(cos)).getJSONArray("subnames").put(new
				 * JSONObject("{text:'"+jmv.getString("text")+"'}")); offset++;
				 * //移除个数增加1 } }
				 */

				out.print("{course:'" + course + "'");
				out.print(",root:");
				out.print(js.toString());
				out.print("}");

			} else if("term_cmbo".equals(par)){ // 表示请求学期（oracle方案）名称列表
				JSONArray js = DAOFactory.getDatasetDAOInstance().getSchList();           
				out.print("{root:");
				//js.put("{\"text\":\"all\"}");
				out.print(js.toString());
				out.print("}");
				
			}
			out.flush();
			out.close();
			// form.reset(mapping, request);
		} catch (Exception e) {
			// out.print("{success:false,errors:[{id:\"ExcuteSQL\",msg:\"数据访问出错："+
			// r + "\"}]}");
			throw new NullPointerException("getlist error");
		}
	}
}
